import requests


class TwitchApiClient:

    def __init__(self, client_id, client_secret):
        self._auth_url = 'https://id.twitch.tv/oauth2/token'
        self.base_url = 'https://api.twitch.tv/helix'
        self._client_id = client_id
        self._client_secret = client_secret
        self._bearer = None
        self._authorize()

    def _authorize(self):
        params = {
            'client_id': self._client_id,
            'client_secret': self._client_secret,
            'grant_type': 'client_credentials'
        }
        response = requests.post(self._auth_url, params)
        json = response.json()
        self._bearer = json['access_token']

    def user(self, user):
        headers = {
            'Authorization': 'Bearer {0}'.format(self._bearer),
            'Client-ID': self._client_id
        }
        response = requests.get("{0}/users?login={1}".format(self.base_url, user), headers=headers)
        return response.json()

    def streams(self, query):
        headers = {
            'Authorization': 'Bearer {0}'.format(self._bearer),
            'Client-ID': self._client_id
        }
        url = "{0}/search/channels?query={1}&live_only=true".format(self.base_url, query)
        response = requests.get(url, headers=headers)
        return response.json()

    def subscriptions(self):
        headers = {
            'Authorization': 'Bearer {0}'.format(self._bearer),
            'Client-ID': self._client_id
        }
        url = "{0}/eventsub/subscriptions".format(self.base_url)
        response = requests.get(url, headers=headers)
        print(response.text)
        exit()
        return response.json()
